//
//  MpaassWebViewController.m
//  RNMpaas
//
//  Created by GJS on 2022/6/24.
//

#import "MpaassWebViewController.h"
#import "Masonry.h"
#import <WebKit/WebKit.h>
#import "RCTUtils.h"
#import "RCTConvert.h"
#import "MBProgressHUD.h"

#ifndef NSStringMultiline
#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]
#endif

@interface MpaassWebViewController () <WKNavigationDelegate, WKUIDelegate>

@property (strong, nonatomic) WKWebView *webView;
@property (strong, nonatomic) WKWebView *fakeWKWebView;

@end

@implementation MpaassWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColor.whiteColor;
    self.navigationController.navigationBarHidden = NO;
    [self setupAndLoad];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.webView animated:YES];
    hud.label.text = @"加载中...";
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = self.originNavigationBarHidden;
}

- (WKWebView *)webView {
    if (_webView == nil) {
        _webView = WKWebView.new;
        _webView.navigationDelegate = self;
        _webView.UIDelegate = self;
        [self.view addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (@available(iOS 11.0, *)) {
                make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft);
                make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight);
                make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
                make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
            } else {
                make.leading.trailing.top.bottom.equalTo(self.view);
            }
        }];
    }
    return _webView;
}

- (void)setWebViewUA:(NSString *)customUA completeHandler:(void (^)(void))completeHandler {
    if (customUA == nil) {
        if (completeHandler) {
            completeHandler();
        }
        return;
    }
    NSString *ua = customUA;
    self.fakeWKWebView = WKWebView.new;
    if (@available(iOS 12.0, *)){
        //由于iOS12的UA改为异步，所以不管在js还是客户端第一次加载都获取不到，所以此时需要先设置好再去获取
        NSString *userAgent = [self.webView valueForKey:@"applicationNameForUserAgent"];
        if (![userAgent containsString:ua]) {
            //NSString *newUserAgent = [NSString stringWithFormat:@"%@%@", userAgent, ua]; // 追加
            NSString *newUserAgent = [NSString stringWithFormat:@"%@", ua]; // 完全替换
            [self.webView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
            NSLog(@"%@>>>%@>>>>>",userAgent,newUserAgent);
        }
    }
    __weak typeof(self) weakSelf = self;
    [self.fakeWKWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *userAgent = result;
        
        if ([userAgent rangeOfString:ua].location == NSNotFound) {
            //NSString *newUserAgent = [NSString stringWithFormat:@"%@%@", userAgent, ua]; // 追加
            NSString *newUserAgent = [NSString stringWithFormat:@"%@", ua]; // 完全替换
            NSLog(@"%@=>=>=>%@=>=>=>",userAgent,newUserAgent);
            //不添加以下代码则只是在本地更改UA，网页并未同步更改
            if (@available(iOS 9.0, *)) {
                [self.webView setCustomUserAgent:newUserAgent];
            } else {
                [self.webView setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
            }
        }
        weakSelf.fakeWKWebView = nil;
        if (completeHandler) {
            completeHandler();
        }
    }]; //加载请求必须同步在设置UA的后面
}

- (void)setupAndLoad {
    __weak typeof (self) weakSelf = self;
    [self setWebViewUA:self.userAgent completeHandler:^{
        RCTExecuteOnMainQueue(^{
            [weakSelf loadSource];
        });
    }];
}

- (void)loadSource {
    // Check for a static html source first
    NSString *html = [RCTConvert NSString:self.source[@"html"]];
    if (html) {
        NSURL *baseURL = [RCTConvert NSURL:self.source[@"baseUrl"]];
        if (!baseURL) {
            baseURL = [NSURL URLWithString:@"about:blank"];
        }
        [self.webView loadHTMLString:html baseURL:baseURL];
        return;
    }

    NSURLRequest *request = [RCTConvert NSURLRequest:self.source];

    // Because of the way React works, as pages redirect, we actually end up
    // passing the redirect urls back here, so we ignore them if trying to load
    // the same url. We'll expose a call to 'reload' to allow a user to load
    // the existing page.
    if ([request.URL isEqual:self.webView.URL]) {
        return;
    }
    if (!request.URL) {
        // Clear the webview
        [self.webView loadHTMLString:@"" baseURL:nil];
        return;
    }
    [self.webView loadRequest:request];
}

- (void)addWater{

    [self.webView evaluateJavaScript:[self getWaterMarkString] completionHandler:nil];

      //1 获取JSContext

//    JSContext *context = [self.myWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

//      NSString *jsMethondAction = @"watermark_show({ watermark_txt: \"aaaad\",watermark_y:65});";

//      [context evaluateScript:jsMethondAction];

    // 2
    [self.webView evaluateJavaScript:[NSString stringWithFormat:@"watermark_show({\
                                      watermark_txt: \"%@\",\
                                      watermark_rows:20,\
                                      watermark_cols:4,\
                                      });", self.waterString] completionHandler:nil];

}

// 要注入的js添加水印方法

- (NSString *)getWaterMarkString{

    NSString *str = NSStringMultiline(function watermark_show(settings) {
        
        var defaultSettings={

            watermark_txt: "",

            watermark_x : 50,

            watermark_y : 50,

            watermark_cols : 3,

            watermark_rows : 4,

            watermark_x_space : 150,

            watermark_y_space : 160,

            watermark_color : '#000000',

            watermark_alpha : 0.2,

            watermark_fontsize : '20px',

            watermark_font : '微软雅黑',

            watermark_width : 100,

            watermark_height : 70,

            watermark_angle : 20

        };

        if(arguments.length===1&&typeof arguments[0] ==="object" ){

            var src=arguments[0]||{};

            for(key in src){

                if(src[key]&&defaultSettings[key]&&src[key]===defaultSettings[key])

                    continue;

                else if(src[key])

                    defaultSettings[key]=src[key];

            }

        }

        var oTemp = document.createDocumentFragment();

        var page_width = Math.max(document.body.scrollWidth,document.body.clientWidth,window.screen.width);

        var page_height = Math.max(document.body.scrollHeight,document.body.clientHeight,window.screen.height);

        if (defaultSettings.watermark_cols == 0 || (parseInt(defaultSettings.watermark_x + defaultSettings.watermark_width *defaultSettings.watermark_cols + defaultSettings.watermark_x_space * (defaultSettings.watermark_cols - 1)) > page_width)) {

            defaultSettings.watermark_cols = parseInt((page_width-defaultSettings.watermark_x+defaultSettings.watermark_x_space) / (defaultSettings.watermark_width + defaultSettings.watermark_x_space));

            defaultSettings.watermark_x_space = parseInt((page_width - defaultSettings.watermark_x - defaultSettings.watermark_width * defaultSettings.watermark_cols) / (defaultSettings.watermark_cols - 1));

        }

        if (defaultSettings.watermark_rows == 0 || (parseInt(defaultSettings.watermark_y + defaultSettings.watermark_height * defaultSettings.watermark_rows + defaultSettings.watermark_y_space * (defaultSettings.watermark_rows - 1)) > page_height)) {

            defaultSettings.watermark_rows = parseInt((defaultSettings.watermark_y_space + page_height - defaultSettings.watermark_y) / (defaultSettings.watermark_height + defaultSettings.watermark_y_space));

            defaultSettings.watermark_y_space = parseInt(((page_height - defaultSettings.watermark_y) - defaultSettings.watermark_height * defaultSettings.watermark_rows) / (defaultSettings.watermark_rows - 1));

        }

        var x;

        var y;

        for (var i = 0; i < defaultSettings.watermark_rows; i++) {

            y = defaultSettings.watermark_y + (defaultSettings.watermark_y_space + defaultSettings.watermark_height) * i;

            for (var j = 0; j < defaultSettings.watermark_cols; j++) {

                x = defaultSettings.watermark_x + (defaultSettings.watermark_width + defaultSettings.watermark_x_space) * j;

                var mask_div = document.createElement('div');

                mask_div.id = 'mask_div' + i + j;

                mask_div.appendChild(document.createTextNode(defaultSettings.watermark_txt));

                mask_div.style.webkitTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.MozTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.msTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.OTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.transform = "rotate(-" + defaultSettings.watermark_angle + "deg)";

                mask_div.style.visibility = "";

                mask_div.style.position = "absolute";

                mask_div.style.left = x + 'px';

                mask_div.style.top = y + 'px';

                mask_div.style.overflow = "hidden";

                mask_div.style.zIndex = "9999";

                mask_div.style.opacity = defaultSettings.watermark_alpha;

                mask_div.style.filter="alpha(opacity='10')";

                mask_div.style.fontSize = defaultSettings.watermark_fontsize;

                mask_div.style.fontFamily = defaultSettings.watermark_font;

                mask_div.style.color = defaultSettings.watermark_color;

                oTemp.appendChild(mask_div);

            };

        };

        document.body.appendChild(oTemp);

});

    return str;

}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [MBProgressHUD hideHUDForView:webView animated:YES];
    if (self.flagAddWater) {
        [self addWater];
    }
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [MBProgressHUD hideHUDForView:webView animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
